<template>
  <div class="app-container home">
    <el-form ref="createForm" v-model="clusterForm" label-suffix="：" inline
             label-width="160px" label-position="left">
      <el-card shadow="never" header="基础信息" class="card_margin">
        <el-row>
          <el-col :span="8">
            <el-form-item label="集群编号" required>
              <el-input v-model="cluster.hclusterId" style="width:300px;"
                        placeholder="集群编号只能是字母和数字的组合"/>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="Kingwow版本" required>
              <el-select v-model="cluster.version" clearable placeholder="请选择" style="width:350px;">
                <el-option v-for="item in version_list" :key="item.version"
                           :label="item.version+' - '+item.packageName"
                           :value="item.id">
                </el-option>
              </el-select>
              &nbsp;&nbsp;&nbsp;&nbsp;
              <el-button type="text" @click="showAddPackage=true">添加版本</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card shadow="never" header="集群配置" class="card_margin">
        <el-card shadow="never" header="服务端口设置" class="card_margin">
          <el-row>
            <el-col :span="6">
              <el-form-item label="manEng服务端口" required>
                <el-input-number v-model="cluster.mgPort" :min="1024" :max="65535"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="transEng服务端口" required>
                <el-input-number v-model="cluster.tgPort" :min="1024" :max="65535"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="transEng内部端口" required>
                <el-input-number v-model="cluster.tgInnerPort" :min="1024" :max="65535"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="calEng服务端口" required>
                <el-input-number v-model="cluster.cgPort" :min="1024" :max="65535"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="MySQL端口" required>
                <el-input-number v-model="cluster.cgMysqlPort" :min="1024" :max="65535"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="datEng服务端口" required>
                <el-input-number v-model="cluster.dgPort" :min="1024" :max="65535"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
        <el-card  shadow="never" class="card_margin">
          <template slot="header">
            子集群设置
            <el-button type="text" style="float: right;" @click="showAddMachine=true" >
              <el-icon class="el-icon-plus"/> 添加机器
            </el-button>
          </template>
          <el-row >
            <el-col>
              <el-collapse v-model="activeNames" accordion>
                <el-collapse-item :name="cluster.clusterId" :key="cluster.clusterId" v-for="cluster in zoneList">
                  <template slot="title" style="width: 100%;">
                    <div style="width: 100%;display: flex;justify-content: space-between;margin-right: 10px;">
                    Zone
                      <el-button icon="el-icon-delete" type="text"
                                 @click.stop="delSubCluster(cluster.clusterId)"
                                 :title="zoneList.length==1?'至少需要一个子集群':''"
                                 :disabled="zoneList.length==1">
                        删除Zone
                      </el-button>
                    </div>
                  </template>
                  <el-table :data="cluster.nodes" border>
                    <el-table-column label="机器">
                      <template slot-scope="scope">
                        <el-select
                          :loading="machineLoading"
                          v-model="scope.row.ip"
                          filterable clearable
                          remote size="small"
                          placeholder="请输入IP并选择"
                          @focus="getAllMachine()"
                          :remote-method="getAllMachine">
                          <el-option
                            v-for="item in machineList"
                            :key="item.ip"
                            :label="item.ip"
                            :title="disabledMachinTitle(item)"
                            :disabled="checkMachineStatus(item)"
                            :value="item.ip">
                          </el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="部署manEng" >
                      <template slot-scope="scope">
                        <el-checkbox :true-label="1" :false-label="0" v-model="scope.row.mg"/>
                      </template>
                    </el-table-column>
                    <el-table-column label="部署transEng">
                      <template slot-scope="scope">
                        <el-checkbox :true-label="1" :false-label="0" v-model="scope.row.tg"/>
                      </template>
                    </el-table-column>
                    <el-table-column label="部署calEng">
                      <template slot-scope="scope">
                        <el-checkbox :true-label="1" :false-label="0" v-model="scope.row.cg"/>
                      </template>
                    </el-table-column>
                    <el-table-column label="部署datEng">
                      <template slot-scope="scope">
                        <el-checkbox :true-label="1" :false-label="0" v-model="scope.row.dg"/>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作">
                      <template slot-scope="scope">
                        <el-button type="text" @click.stop="delMachine(cluster.clusterId,scope.$index)" :disabled="cluster.nodes.length==1">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                  <el-row  style="text-align: center;border:1px dashed #bbb;margin-top:15px;">
                    <el-col>
                      <el-button type="text" @click="addMachine(cluster.clusterId)" :disabled="cluster.nodes.length>=10">
                        <el-icon class="el-icon-plus"/> 新增机器
                      </el-button>
                    </el-col>
                  </el-row>
                </el-collapse-item>
              </el-collapse>
            </el-col>
          </el-row>
          <el-row  style="text-align: center;border:1px dashed #bbb;margin-top:15px;">
            <el-col>
              <el-button type="text" @click="addSubCluster" :disabled="zoneList.length>=6">
                <el-icon class="el-icon-plus"/> 新增Zone
              </el-button>
            </el-col>
          </el-row>
        </el-card>
      </el-card>
      <el-card shadow="never" header="安装路径"  class="card_margin">
        <el-row>
          <el-col>
            <el-form-item label="部署模式">
              <el-radio-group v-model="cluster.dataMode">
                <el-radio-button :label="0">基本模式</el-radio-button>
                <el-radio-button :label="1">高性能模式</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="软件安装目录">
              <el-input v-model="cluster.softPath" size="small" placeholder="基于安装用户主目录的安装目录名称" style="width:800px"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row  v-if="cluster.dataMode==0">
          <el-col>
            <el-form-item label="数据盘路径">
              <el-input v-model="cluster.dataPath" size="small" placeholder="请输入数据存储磁盘目录" style="width:800px"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row  v-if="cluster.dataMode==1">
          <el-col>
            <el-form-item label="datEng数据盘路径">
              <el-select v-model="cluster.dgData" size="small" style="width:800px"
                         placeholder="请输入datEng数据盘路径，可输入多个路径"
                         multiple filterable allow-create>
                <el-option
                  v-for="item in cluster.dgData"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
              <br/>高性能模式下建议输入至少4个数据盘，最多不大于16个数据盘
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="cluster.dataMode==1">
          <el-col>
            <el-form-item label="transEng数据盘路径">
              <el-input v-model="cluster.tgData" size="small" style="width:800px" placeholder="请输入transEng数据盘路径"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="cluster.dataMode==1">
          <el-col>
            <el-form-item label="transEng日志盘路径">
              <el-input v-model="cluster.tgLog" size="small" style="width:800px" placeholder="请输入transEng日志盘路径"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="cgroup目录">
              <el-checkbox v-model="cluster.enableCgp" :true-label="1" :false-label="0">
                启用
              </el-checkbox>
              <el-input v-if="cluster.enableCgp==1" v-model="cluster.cgroupDir"
                        size="small" style="width:740px" placeholder="请输入cgroup目录名称"/>
              <br/>
              <span v-if="cluster.enableCgp==1">cgroup目录为系统/sys/fs/cgroup/cpu/下的目录，需要rwx权限</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="附加信息">
              <el-input v-model="cluster.extra" size="small" style="width:800px" placeholder="请输入标准JSON格式的附加信息"/>
              <br/>标准格式JSON附加信息,如：{"user_name":"admin"}
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card shadow="never" class="card_margin">
        <el-row>
          <el-col :span="18">
            <div style='font-size: 14px;color: #48576a;font-family:"Microsoft Yahei", sans-serif;'>
              <span v-if="checkReslut.length>0" style="color: red;">错误提示:</span><br/>
              <div v-for="r in checkReslut" style="text-indent: 20px;">{{r.msg}}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <el-button type="info" style="float:right;margin-left: 20px;margin-right: 20px;"
                       :loading="deployLoading" @click="backTo">取消</el-button>
            <el-button type="success" style="float:right"
                       :loading="deployLoading" @click="deployCluster">提交</el-button>
          </el-col>
        </el-row>
      </el-card>
    </el-form>

    <upload-file v-if="showAddPackage" @closeDrawer="getAllVersionInfo"/>
    <add-machine v-if="showAddMachine" @closeDrawer="showAddMachine = false"/>
  </div>
</template>

<script>
import { listNoPage } from "@/api/attachments/attachments";
import { listMachine } from "@/api/machine/machine";
import {addPrecheck} from "@/api/cluster/cluster";
import UploadFile from "@/views/attachments/upload";
import AddMachine from "@/views/machine/addMachine";
export default {
  name: "Index",
  components:{
    UploadFile,
    AddMachine
  },
  data() {
    return {
      cluster:{
        "hclusterId":"",
        "version":"",
        "mgPort":2500,
        "tgPort":2700,
        "tgInnerPort":2701,
        "cgPort":2800,
        "cgMysqlPort":2880,
        "dgPort":2600,
        "dataMode":0,
        "softPath":"kingwow",
        "dataPath":"/data",
        "dgData":[],
        "tgData":"",
        "tgLog":"",
        "extra":"",
        "enableCgp":0,
        "cgroupDir":"",
      },
      showAddPackage:false,
      showAddMachine:false,
      activeNames:0,
      zoneList:[{clusterId:0,nodes:[{ip:"",mg:1,tg:1,cg:1,dg:1}]}],
      zoneSize:0,
      machineList:[],
      machineLoading:false,
      showCreateMachine:false,
      deployLoading: false,
      checkReslut:[],
      clusterForm: {},
      version_list: [],
    };
  },
  created() {
    this.getAllVersionInfo();
  },
  methods: {
    backTo(){
      this.$router.push("/");
    },
    addSubCluster(){
      this.zoneList.push({clusterId:++this.zoneSize,nodes:[{ip:"",mg:0,tg:0,cg:0,dg:0}]})
      this.activeNames=this.zoneSize
    },
    delSubCluster(id){
      let index = this.zoneList.findIndex(z =>{
        return z.clusterId==id
      });
      this.zoneList.splice(index,1)
    },
    addMachine(clusterId){
      let cluster = this.zoneList.find(z=>{
        return z.clusterId == clusterId;
      })
      cluster.nodes.push({ip:"",mg:0,tg:0,cg:0,dg:0});
    },
    delMachine(clusterId,idx){
      let cluster = this.zoneList.find(z=>{
        return z.clusterId == clusterId;
      })
      let index = cluster.nodes.findIndex((z,fidx) =>{
        return fidx==idx
      });
      cluster.nodes.splice(index,1)
    },
    async getAllMachine(ip){
      this.showAddMachine = false;
      this.machineLoading = true;
      let param = {"pageable":"no"};
      if(ip && ip!="") param["ip"] = ip;
      const res = await listMachine(param);
      this.machineLoading=false;
      if (res.code == 200) {
        this.machineList = res.rows;
        this.zoneList.forEach(cs=>{
          cs.nodes.forEach(is=>{
            let idx = this.machineList.findIndex(mc=>{
              return mc.ip==is.ip;
            })
            if(idx>-1){
              this.machineList.splice(idx,1);
            }
          })
        })
      }
    },
    async deployCluster() {
      this.checkReslut=[]
      //验证基本要素
      if (this.cluster.hclusterId == "") {
        this.notifyMsg("集群编号不能为空！");
        return;
      }
      if (this.cluster.version == "") {
        this.notifyMsg("请选择Kingwow版本！")
        return;
      }
      let validate = true;
      let totalMg = 0, totalTg = 0, totalCg = 0, totalDg = 0;
      this.zoneList.forEach(zone => {
        /*if (!zone.cluster_name || zone.cluster_name == "") {
            this.notifyMsg("Zone名称不能为空！");
            validate = false
            return;
        }*/

        zone.nodes.forEach(ipc => {
          if (ipc.ip == "") {
            this.notifyMsg("请选择机器IP！");
            validate = false
            return;
          }
          if (ipc.mg + ipc.cg + ipc.dg + ipc.tg == 0) {
            this.notifyMsg("机器:"+ipc.ip+"，角色【manEng、transEng、calEng、datEng】至少需要选择一个！");
            validate = false
            return;
          }
          totalMg += ipc.mg;
          totalTg += ipc.tg;
          totalCg += ipc.cg;
          totalDg += ipc.dg;
        })
        if (!validate) return;
      });
      if (totalMg == 0) {
        this.notifyMsg("在所有Zone中至少需要部署一个manEng！");
        validate = false
        return;
      }
      if (totalTg == 0) {
        this.notifyMsg("在所有Zone中至少需要部署一个transEng！");
        validate = false
        return;
      }
      if (totalCg == 0) {
        this.notifyMsg("在所有Zone中至少需要部署一个calEng！");
        validate = false
        return;
      }
      if (totalDg == 0) {
        this.notifyMsg("在所有Zone中至少需要部署一个datEng！");
        validate = false
        return;
      }
      //验证通过
      if (validate) {
        if (this.cluster.softPath == "") {
          this.notifyMsg("软件安装路径不能为空！");
          validate = false
          return;
        }
        if(this.cluster.dataMode==0){
          if (this.cluster.dataPath=="") {
            this.notifyMsg("数据盘路径不能为空！");
            validate = false
            return;
          }
        }else{
          if (this.cluster.dgData.length<4) {
            this.notifyMsg("datEng数据盘建议不少于4个！");
            validate = false
            return;
          }else if(this.cluster.dgData.length>16){
            this.notifyMsg("datEng数据盘建议不大于16个！");
            validate = false
            return;
          }
          if (this.cluster.tgData=="") {
            this.notifyMsg("transEng数据盘路径不能为空！");
            validate = false
            return;
          }
          if (this.cluster.tgLog=="") {
            this.notifyMsg("transEng日志盘路径不能为空！");
            validate = false
            return;
          }
        }
        if (this.cluster.enableCgp == 1 && this.cluster.cgroupDir=="") {
          this.notifyMsg("启用cgroup时cgroup目录名称不能为空！");
          validate = false
          return;
        }
      }
      if (validate) {
        //验证机器角色IP 端口是否可用，验证安装路径是否存在则拥有读写权限
        this.deployLoading=true;
       addPrecheck({"cluster": this.cluster, "zones": this.zoneList}).then(res =>{
         if(res.code==200){
           if(res.data.check && res.data.check.length>0){
             this.checkReslut = res.data.check;
           }else{
             this.$confirm('恭喜，集群一键部署任务创建成功！', '提示', {
               confirmButtonText: '查看任务详情',
               cancelButtonText: '返回集群列表',
               type: 'success'
             }).then(() => {
               this.$router.push({
                 path: "taskLog",
                 query: {
                   taskId:res.task_id,
                 },
               });
             }).catch(() => {
               this.backTo();
             });

           }
         }
        }).finally(()=>{
         this.deployLoading=false;
       });

      }
    },
    notifyMsg(msg,type){
      this.$notify({
        message: msg,
        type: type==undefined?'error':'info',
        duration: 2000,
      });
    },
    async getAllVersionInfo() {
      this.showAddPackage = false;
      this.version_list = await listNoPage({"comment":"kingwow"});
    },
    checkMachineStatus(row){
      if(row.status==='submit' || row.status==='deleted')
        return false;
      return false;
    },
    disabledMachinTitle(row){
      if(row.status==='submit' || row.status==='deleted')
        return "机器正在创建或删除中，无法选择";
      return "";
    },
  }
};
</script>

<style scoped>
.card_margin{
  margin-bottom: 15px;
}
</style>
